<template>
    <div>
        <Table :columns="columns" :paginatedData="paginatedData" :btnList="btnList" :btnListTable="btnListTable"
            :isFixedColumn="true" :columnWidth="160" :isMore="false" :tableLoading="loading" :total="total"
            @pageSize="handlePageSize" @currentPage="handleCurrentPage">
            <!-- 条件组,插槽 -->
            <template #default>
                <el-form :inline="true" :model="formBtnList" class="demo-form-inline" @submit.native.prevent>
                    <el-form-item label="用户名">
                        <el-input v-model="formBtnList.user_name" placeholder="请输入用户名" style="width: 160px"/>
                    </el-form-item>
                    <el-form-item label="用户ID">
                        <el-input v-model="formBtnList.user_id" placeholder="请输入用户ID" style="width: 160px"/>
                    </el-form-item>
                    <el-form-item label="反馈内容">
                        <el-input v-model="formBtnList.content" :prefix-icon="Search" placeholder="请输入反馈内容" style="width: 160px"/>
                    </el-form-item>
                    <el-form-item label="分类">
                        <el-select v-model="formBtnList.tag" placeholder="分类" 举报人 @change="handleOnSelect" style="width: 100px">
                            <el-option v-for="item in tagOptions" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="发布时间">
                        <el-date-picker v-model="dateList" style="width: 240px" type="daterange" unlink-panels range-separator="-"
                        start-placeholder="开始日期" end-placeholder="结束日期" :shortcuts="shortcuts" value-format="YYYY-MM-DD"
                        format="YYYY-MM-DD" @change="handleDateChange" />
                    </el-form-item>
                    <!-- <el-form-item label="">
                        <el-input v-model="formBtnList.search" :prefix-icon="Search" placeholder="请输入关键字/用户ID" />
                    </el-form-item> -->
                </el-form>
            </template>
        </Table>

        <!-- 弹窗 -->
        <DialogCom ref="dialogCom" :dialogVisible="dialogVisible" :btnLoading="btnLoading" :tableTitle="tableTitle"
            :formData="formData" :ruleForm="ruleForm" :rules="rules" @beforeClose="beforeClose"
            @dialogSwitch="dialogSwitch" @submitForm="submitForm" />
    </div>
</template>

<script setup lang='ts' name="feedback">
import { ref, reactive, onMounted } from 'vue'
import type { FormRules } from 'element-plus'
import Table from '@/components/Table.vue';
import DialogCom from '@/components/DialogCom.vue';
import { require } from '@/utils/require';
import { Search } from '@element-plus/icons-vue'
import { feedback, feedbackAdd, feedbackDel, feedbackEdit } from "@/api/feedback/feedback.ts"
// 表格相关 开始
const loading = ref(false)
// 表头数据
const columns = ref([
    { prop: 'feedback_id', label: '反馈ID', width: 100 },
    { prop: 'tag', label: '分类', width: 90 },
    { prop: 'content', label: '反馈内容', width: "" },
    { prop: 'user_id', label: '用户ID', width: 150 },
    { prop: 'user_name', label: '用户名', width: 140 },
    { prop: 'user_phone', label: '用户手机', width: 170 },
    { prop: 'publish_time', label: '发布时间', width: 180 },
    // { prop: 'user_email', label: '用户邮箱', width: 240 },
]);
// 表格数据
const paginatedData = ref([]);
// 查询条件
const formBtnList = reactive({
    // search: '',
    user_name:'',
    user_id:'',
    content:'',
    tag:'',
    time_start:'',
    time_end:'',
    page_size: 10,
    page: 1,
})
const dateList = ref([])
let tagOptions = ref([
  {
    value: '',
    label: '全部',
  },
  {
    value: 'APP',
    label: 'APP',
  },
  {
    value: '产品',
    label: '产品',
  },
  {
    value: '其他',
    label: '其他',
  },
])
const handleOnSelect = () => {
  handInquire()
}
// 日期快速选择
const shortcuts = [
  {
    text: '近1周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '近30天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '近90天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]
// 日期选择
const handleDateChange = () => {
  formBtnList.time_start = dateList.value[0]
  formBtnList.time_end = dateList.value[1]
}

const total = ref(0)
// 查询
const handInquire = () => {
    loading.value = true
    feedback(formBtnList).then((res: any) => {
        if (res.code === 200) {
            total.value = res.data.total
            if (res.data.total === 0) {
                paginatedData.value = []
                ElMessage.error(`反馈内容不存在`)
                return
            }
            const processedData = res.data.feedbacks.map((item: Object) => {
                return {
                    ...item,
                    judData: item.accept
                };
            });
            paginatedData.value = processedData
        } else {
            paginatedData.value = []
            ElMessage.error(`请求错误: ${res.msg}`)
        }
    }).catch((error: any) => {
        ElMessage.error(`请求错误: ${error.msg}`)
    }).finally(() => {
        loading.value = false
    })
}
interface RuleForm {
    tag: string
    user_name: string
    email: string
    phone: string
    content: string
}
// 表单数据
// const ruleForm = reactive({})
// // 重置表单方法
// const resetForm = (initialData?: Partial<RuleForm>) => {
//     Object.assign(ruleForm, {
//         tag: '',
//         user_name: '',
//         email: '',
//         phone: '',
//         content: '',
//         ...(initialData || {}),
//     });
// };
// // 新增
// const handAddAccount = () => {
//     resetForm();
//     tableTitle.value = '请填写信息'
//     dialogVisible.value = true
// }

// 接纳 / 不接纳
const rece = (data: object, text: string) => {
    ElMessageBox.confirm(
        `是否${text}?`,
        `${text}`,
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
        }
    ).then(() => {
        feedbackEdit(data).then((res: any) => {
            if (res.code === 200) {
                ElMessage({
                    message: '成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(`请求错误: ${res.msg}`)
            }
        }).catch(() => {
        }).finally(() => {
            handInquire()
        })
    })
}
// 接纳
const handReceiving = (row: object, index: number) => {
    let para = {
        feedback_id: row.feedback_id,
        accept: '1',
    }
    rece(para, '接纳')
}
// 已接纳
const handNoReceiving = (row: object, index: number) => {
    let para = {
        feedback_id: row.feedback_id,
        accept: '0',
    }
    rece(para, '取消接纳')
}
// 重置
const handDerived = () => {
    // console.log('重置')
    // formBtnList.search = ''
    formBtnList.user_id = ''
    formBtnList.user_name= ''
    formBtnList.tag= ''
    formBtnList.content=''
    formBtnList.time_start=''
    formBtnList.time_end = ''
    formBtnList.page=1
    formBtnList.page_size=10
    dateList.value=[]
    handInquire()
}
// 按钮组
const btnList = [
    { name: '查询', type: 'primary', click: handInquire, icon: '' },
    { name: '重置', type: 'success', click: handDerived, icon: '' },
    // { name: '新增', type: 'primary', click: handAddAccount, icon: '' },
]

// 删除
const del = (row: object, index: number) => {
    ElMessageBox.confirm(
        '是否删除?',
        '删除',
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
        }
    ).then(() => {
        feedbackDel(row.feedback_id).then((res: any) => {
            if (res.code === 200) {
                ElMessage({
                    message: '成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(`请求错误: ${res.msg}`)
            }
        }).catch(() => {
        }).finally(() => {
            handInquire()
        })
    })
}
// 操作列按钮组
const btnListTable = ref([
    { name: '接纳', type: 'success', click: handReceiving, judgment: true, isShow: ['0'], },
    { name: '已接纳', type: 'info', click: handNoReceiving, judgment: true, isShow: ['1'], },
    { name: '删除', type: 'danger', click: del },
])
// 分页事件触发
const handlePageSize = (pageSize: number) => {// 每页大小
    // console.log('handlePageSize', pageSize);
    formBtnList.page_size = pageSize
    handInquire()
};
const handleCurrentPage = (currentPage: number) => {// 页码
    // console.log('handleCurrentPage', currentPage);
    formBtnList.page = currentPage
    handInquire()
};
// 表格相关 结束

// 弹窗相关
const dialogCom = ref<InstanceType<typeof DialogCom>>();
const btnLoading = ref(false)
// 选择框假数据
const jsOptions = ref([
    { label: 'APP', value: '1' },
    { label: '产品', value: '2' },
    { label: '其它', value: '3' },
])
// 表单控件数据
const formData = reactive([
    { type: 'select', label: '分类', prop: 'tag', span: 24, placeholder: '请选择', options: jsOptions, },
    { type: 'input', label: '用户名', prop: 'user_name', span: 24, placeholder: '请输入' },
    { type: 'input', label: '手机', prop: 'phone', span: 24, placeholder: '请输入' },
    { type: 'input', label: '邮箱', prop: 'email', span: 24, placeholder: '请输入' },
    { type: 'textarea', label: '反馈内容', prop: 'content', span: 24, placeholder: '请输入', maxlength: 200, autosize: { minRows: 3, maxRows: 5 }, },
])
// 表单校验配置
const rules = reactive<FormRules<RuleForm>>({
    user_name: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
    ],
    email: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
        { min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur' },
    ],
})
// 弹窗 确认按钮
const submitForm = ((ruleFormData: any) => {
    btnLoading.value = true
    feedbackAdd(ruleFormData).then((res: any) => {
        if (res.code === 200) {
            if (dialogCom.value) {
                dialogCom.value.cancelClick(); // 调用子组件方法
            }
            ElMessage({
                message: '成功',
                type: 'success',
            })
        } else {
            ElMessage.error(`请求错误: ${res.msg}`)
        }
    }).catch((error: any) => {
        ElMessage.error(`请求错误: ${error.msg}`)
        btnLoading.value = false
    }).finally(() => {
        btnLoading.value = false
        handInquire()
    })
})
// 标题
const tableTitle = ref('');
const dialogVisible = ref(false);
const beforeClose = () => {
    dialogVisible.value = false;
}
const dialogSwitch = (row: object) => {
    console.log('row: ', row);

}
onMounted(() => {
    handInquire()
})
</script>
<style lang='scss' scoped>
.demo-form-inline {
    .el-input {
        width: 265px;

    }

    :deep(.el-input__wrapper) {
        border-radius: 20px;
    }

}
</style>